package com.zhongkeruan.user.controller;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.zhongkeruan.user.responsedata.ResponseData;
import com.zhongkeruan.user.service.IUserService;
import com.zhongkeruan.user.vo.User;

@RestController
@RequestMapping(value = "/users")
public class UserController {

	@Autowired
	private IUserService userService;

	@RequestMapping(value = "/", method = RequestMethod.POST)
	public ResponseData<User> add(@RequestBody User user) throws Exception{
		this.userService.save(user);
		List<User> data = new ArrayList<User>();
		data.add(user);
		return new ResponseData<User>(200,"请求成功!",data);
	}

	@RequestMapping(value = "/delete/{id}", method = RequestMethod.DELETE)
	public ResponseData<User> del(@PathVariable("id") Long id)throws Exception {
		this.userService.delete(id);
		return new ResponseData<User>(200,"删除成功!",null);
	}

	@RequestMapping(value = "/{id}", method = RequestMethod.PUT)
	public ResponseData<User> findByUsername(String userName,@PathVariable("id")Long id) throws Exception{
		this.userService.update(id, userName);
		return new ResponseData<User>(200,"更新成功!",null);
	}
	
	@RequestMapping(value = "/", method = RequestMethod.GET)
	public ResponseData<User> list()throws Exception {
		return new ResponseData<User>(200,"查询成功!",this.userService.findAll());
	}
	
	@RequestMapping(value = "/{id}", method = RequestMethod.GET)
	public ResponseData<User> get(@PathVariable("id")Long id) throws Exception{
		List<User> data = new ArrayList<User>();
		User user = this.userService.findById(id).get();
		data.add(user);
		return new ResponseData<User>(200,"请求成功!",data);
	}
}
